﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ScrewTurn.Wiki;
using System.IO;
using System.Globalization;
using System.Data.SqlClient;

public partial class GetMacro : System.Web.UI.Page
{
	protected void Page_Load(object sender, EventArgs e)
	{
		if (SessionFacade.LoginKey == null && Settings.PrivateAccess)
		{
			Response.StatusCode = 401;
			Response.Redirect("AccessDenied.aspx");
		}

		if (Request["SetupID"] == null)
		{
			Response.StatusCode = 404;
			Response.Write(Resources.Messages.FileNotFound);
			return;
		}

		//Accessing Database to get the Content and Name of Setup with id = SetupID and Username = SessionFacade.Username
		//The Content is placed into string CurrentContent and Name into CurrentName
		//Requested SetupID must belong to Username (validated in SQL query)
		#region Get Content from DB into CurrentContent and Name into CurrentName
		SqlConnection MyConnection = new SqlConnection(Constants.NMRUserDataConStr);
		MyConnection.Open();
		SqlCommand GetSetupContentByID = MyConnection.CreateCommand();
		GetSetupContentByID.CommandText = @"SELECT        setups.[content] AS [Content], setups.[name] AS [Name]
FROM            relation_setups_to_users INNER JOIN
                         setups ON relation_setups_to_users.setupid = setups.id
WHERE        (relation_setups_to_users.username = '##username##') AND (setups.id = ##id##)".
			Replace("##username##", SessionFacade.Username).Replace("##id##", Request["SetupID"]);

		SqlDataReader MyReader = GetSetupContentByID.ExecuteReader();
		if (!MyReader.HasRows)
		{
			Log.LogEntry("The search for Setup returned no result.", EntryType.Warning, SessionFacade.Username);
			Response.StatusCode = 404;
			Response.Write(Resources.Messages.FileNotFound);
		}

		MyReader.Read();
		string CurrentContent = MyReader["Content"].ToString();
		string CurrentName = MyReader["Name"].ToString();

		MyReader.Close();
		MyConnection.Close();
		#endregion

		//Create Temporary file (Path - Settings.TempDirectory, Name - GetTempFileName)
		//string TempFile - is to download to client
		#region Create Temp File for Download
		string TempFileName = Path.GetFileName(Path.GetTempFileName());
		string TempFile = Settings.TempDirectory + TempFileName;
		FileStream fs = File.OpenWrite(TempFile);
		StreamWriter sw = new StreamWriter(fs);

		sw.Write(CurrentContent);
		sw.Close();
		fs.Close();
		#endregion

		string mime = "application/octet-stream";
		
		//Form the Response to send Temporary File under the Name CurrentName.mac
		//Then delete temp file
		#region
		Response.Clear();
		Response.AddHeader("content-type", mime);
		Response.AddHeader("content-disposition", "inline;filename=\"" + CurrentName + ".mac\"");

		// Set the cache duration accordingly to the file date/time
		Response.AddFileDependency(TempFile);
		Response.Cache.SetETagFromFileDependencies();
		Response.Cache.SetLastModifiedFromFileDependencies();
		Response.Cache.SetCacheability(HttpCacheability.Public);
		Response.Cache.SetSlidingExpiration(true);
		Response.Cache.SetValidUntilExpires(true);
		Response.Cache.VaryByParams["File"] = true;

		Response.WriteFile(TempFile);
		Response.Flush();
		Response.Close();
		#endregion
		File.Delete(TempFile);
	}
}
